<template>
	<view class="chat-monitor">
		<view class="monitor-header">
			<view class="title">实时会话监控</view>
			<view class="actions">
				<button class="btn refresh-btn" @click="refreshSessions">刷新</button>
				<switch class="auto-refresh-switch" :checked="autoRefresh" @change="toggleAutoRefresh" />
				<text class="auto-refresh-label">{{ autoRefresh ? '自动刷新' : '手动刷新' }}</text>
			</view>
		</view>
		
		<view class="monitor-body">
			<view class="session-list">
				<view class="list-header">活跃会话列表</view>
				<view class="sessions">
					<view
						v-for="(session, index) in activeSessions"
						:key="session.sessionId"
						class="session-item"
						:class="{ 'active': currentSession && currentSession.sessionId === session.sessionId }"
						@click="selectSession(session)"
					>
						<view class="session-header">
							<text class="user-id">用户: {{ session.userId }}</text>
							<text class="session-time">{{ formatTime(session.startTime) }}</text>
						</view>
						<view class="service-info">
							<text class="service-id">客服: {{ getServiceName(session.serviceId) }}</text>
							<text class="session-status" :class="getStatusClass(session.status)">
								{{ getStatusText(session.status) }}
							</text>
						</view>
						<view class="session-preview">
							<text class="last-message">{{ session.lastMessage || '暂无消息' }}</text>
						</view>
					</view>
					
					<view class="no-data" v-if="activeSessions.length === 0">
						<text>暂无活跃会话</text>
					</view>
				</view>
			</view>
			
			<view class="chat-container">
				<view class="chat-header" v-if="currentSession">
					<text class="session-title">会话ID: {{ currentSession.sessionId }}</text>
					<text class="session-info">用户: {{ currentSession.userId }} | 客服: {{ getServiceName(currentSession.serviceId) }}</text>
					<view class="session-actions">
						<button class="btn action-btn" @click="endSession" v-if="currentSession.status === 'ACTIVE'">强制结束</button>
						<button class="btn action-btn" @click="transferSession" v-if="currentSession.status === 'ACTIVE'">转接会话</button>
						<button class="btn action-btn" @click="enterChat">进入会话</button>
					</view>
				</view>
				
				<view class="chat-messages" v-if="currentSession" ref="messagesContainer">
					<view 
						v-for="(message, index) in sessionMessages" 
						:key="index"
						class="message-item"
						:class="{ 
							'user-message': message.senderType === 'USER', 
							'service-message': message.senderType === 'SERVICE' 
						}"
					>
						<view class="message-header">
							<text class="sender-name">{{ message.senderType === 'USER' ? '用户' : '客服' }}</text>
							<text class="message-time">{{ formatTime(message.sendTime) }}</text>
						</view>
						<view class="message-content">{{ message.content }}</view>
					</view>
					
					<view class="no-messages" v-if="sessionMessages.length === 0">
						<text>暂无消息记录</text>
					</view>
				</view>
				
				<view class="chat-placeholder" v-else>
					<text>选择一个会话进行监控</text>
				</view>
			</view>
		</view>
		
		<!-- 转接会话模态框 -->
		<view class="transfer-modal" v-if="showTransferModal">
			<view class="modal-mask" @click="showTransferModal = false"></view>
			<view class="modal-content">
				<view class="modal-header">
					<text class="modal-title">转接会话</text>
					<text class="modal-close" @click="showTransferModal = false">×</text>
				</view>
				<view class="modal-body">
					<view class="form-group">
						<text class="form-label">选择客服</text>
						<picker @change="onServiceChange" :value="selectedServiceIndex" :range="serviceOptions">
							<view class="picker-value">
								{{ selectedServiceIndex > -1 ? serviceOptions[selectedServiceIndex] : '请选择客服' }}
							</view>
						</picker>
					</view>
					<view class="form-group">
						<text class="form-label">转接原因</text>
						<textarea class="form-textarea" v-model="transferReason" placeholder="请输入转接原因"></textarea>
					</view>
				</view>
				<view class="modal-footer">
					<button class="btn cancel-btn" @click="showTransferModal = false">取消</button>
					<button class="btn confirm-btn" @click="confirmTransfer">确认转接</button>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import api from '../api/index.js';
	
	export default {
		name: 'ChatMonitor',
		data() {
			return {
				activeSessions: [],
				currentSession: null,
				sessionMessages: [],
				refreshInterval: null,
				autoRefresh: true,
				loading: false,
				
				// 客服映射
				serviceMap: {},
				
				// 转接相关
				showTransferModal: false,
				transferReason: '',
				serviceOptions: [],
				selectedServiceIndex: -1,
				services: []
			}
		},
		mounted() {
			this.loadServiceMap();
			this.refreshSessions();
			
			if (this.autoRefresh) {
				this.startAutoRefresh();
			}
		},
		beforeDestroy() {
			this.stopAutoRefresh();
		},
		methods: {
			async loadServiceMap() {
				try {
					// 获取所有客服信息
					const res = await api.customerService.getAllServices();
					
					if (res.code === 200 && res.data) {
						const services = res.data;
						
						// 构建客服映射
						this.serviceMap = {};
						services.forEach(service => {
							this.serviceMap[service.id] = service;
						});
						
						// 构建客服选择器选项
						this.services = services;
						this.serviceOptions = services.map(s => `${s.serviceCode} (${s.serviceType === 'HUMAN' ? '人工客服' : '机器人客服'})`);
					} else {
						throw new Error(res.message || '加载客服列表失败');
					}
				} catch (error) {
					console.error('加载客服列表失败:', error);
					uni.showToast({
						title: error.message || '加载客服列表失败',
						icon: 'none'
					});
				}
			},
			
			async refreshSessions() {
				if (this.loading) return;
				
				this.loading = true;
				try {
					// 获取活跃会话列表
					const response = await api.chatSession.getActiveSessions();
					this.activeSessions = response.data || [];
					
					// 如果有当前选中的会话，刷新其消息
					if (this.currentSession) {
						await this.refreshSessionMessages();
					}
				} catch (error) {
					uni.showToast({
						title: '获取会话列表失败',
						icon: 'none'
					});
				} finally {
					this.loading = false;
				}
			},
			
			async refreshSessionMessages() {
				if (!this.currentSession) return;
				
				try {
					// 获取会话消息
					const response = await api.chatSession.getSessionMessages(this.currentSession.sessionId);
					this.sessionMessages = response.data || [];
					
					// 滚动到底部
					this.$nextTick(() => {
						const messagesContainer = this.$refs.messagesContainer;
						if (messagesContainer) {
							messagesContainer.scrollTop = messagesContainer.scrollHeight;
						}
					});
				} catch (error) {
					uni.showToast({
						title: '获取会话消息失败',
						icon: 'none'
					});
				}
			},
			
			selectSession(session) {
				this.currentSession = session;
				this.sessionMessages = [];
				this.refreshSessionMessages();
			},
			
			getServiceName(serviceId) {
				const service = this.serviceMap[serviceId];
				return service ? service.serviceCode : serviceId;
			},
			
			getStatusClass(status) {
				switch(status) {
					case 'ACTIVE': return 'status-active';
					case 'ENDED': return 'status-ended';
					case 'TRANSFERRING': return 'status-transferring';
					default: return '';
				}
			},
			
			getStatusText(status) {
				switch(status) {
					case 'ACTIVE': return '进行中';
					case 'ENDED': return '已结束';
					case 'TRANSFERRING': return '转接中';
					default: return status;
				}
			},
			
			toggleAutoRefresh(e) {
				this.autoRefresh = e.detail.value;
				if (this.autoRefresh) {
					this.startAutoRefresh();
				} else {
					this.stopAutoRefresh();
				}
			},
			
			startAutoRefresh() {
				this.stopAutoRefresh(); // 确保先停止旧的定时器
				this.refreshInterval = setInterval(() => {
					this.refreshSessions();
				}, 10000); // 每10秒刷新一次
			},
			
			stopAutoRefresh() {
				if (this.refreshInterval) {
					clearInterval(this.refreshInterval);
					this.refreshInterval = null;
				}
			},
			
			formatTime(time) {
				if (!time) return '';
				const date = new Date(time);
				return date.toLocaleTimeString();
			},
			
			async endSession() {
				if (!this.currentSession) return;
				
				try {
					const res = await api.chatSession.endSession(this.currentSession.sessionId);
					if (res.code === 200) {
						uni.showToast({
							title: '会话已结束',
							icon: 'success'
						});
						this.refreshSessions();
					} else {
						uni.showToast({
							title: res.message || '结束会话失败',
							icon: 'none'
						});
					}
				} catch (error) {
					uni.showToast({
						title: '结束会话失败',
						icon: 'none'
					});
				}
			},
			
			transferSession() {
				this.showTransferModal = true;
				this.transferReason = '';
				this.selectedServiceIndex = -1;
			},
			
			onServiceChange(e) {
				this.selectedServiceIndex = parseInt(e.detail.value);
			},
			
			async confirmTransfer() {
				if (this.selectedServiceIndex < 0) {
					uni.showToast({
						title: '请选择目标客服',
						icon: 'none'
					});
					return;
				}
				
				if (!this.transferReason.trim()) {
					uni.showToast({
						title: '请输入转接原因',
						icon: 'none'
					});
					return;
				}
				
				try {
					const targetService = this.services[this.selectedServiceIndex];
					
					const res = await api.sessionTransfer.initiateTransfer(
						this.currentSession.sessionId,
						this.currentSession.serviceId,
						targetService.id,
						this.transferReason
					);
					
					if (res.code === 200) {
						uni.showToast({
							title: '转接请求已发送',
							icon: 'success'
						});
					} else {
						uni.showToast({
							title: res.message || '发送转接请求失败',
							icon: 'none'
						});
					}
					
					this.showTransferModal = false;
					this.refreshSessions();
				} catch (error) {
					uni.showToast({
						title: '发送转接请求失败',
						icon: 'none'
					});
				}
			},
			
			enterChat() {
				if (!this.currentSession) return;
				
				// 跳转到客服工作台，加入会话
				uni.navigateTo({
					url: `/pages/customer-service/workbench?sessionId=${this.currentSession.sessionId}`
				});
			}
		}
	}
</script>

<style>
	.chat-monitor {
		height: 100%;
		display: flex;
		flex-direction: column;
	}
	
	.monitor-header {
		padding: 16px;
		background-color: white;
		border-bottom: 1px solid #eee;
		display: flex;
		justify-content: space-between;
		align-items: center;
	}
	
	.title {
		font-size: 18px;
		font-weight: bold;
	}
	
	.actions {
		display: flex;
		align-items: center;
	}
	
	.refresh-btn {
		margin-right: 16px;
	}
	
	.auto-refresh-label {
		margin-left: 8px;
		font-size: 14px;
		color: #666;
	}
	
	.monitor-body {
		flex: 1;
		display: flex;
		overflow: hidden;
	}
	
	.session-list {
		width: 300px;
		border-right: 1px solid #eee;
		display: flex;
		flex-direction: column;
	}
	
	.list-header {
		padding: 12px;
		background-color: #f5f5f5;
		font-weight: bold;
	}
	
	.sessions {
		flex: 1;
		overflow-y: auto;
	}
	
	.session-item {
		padding: 12px;
		border-bottom: 1px solid #eee;
		cursor: pointer;
	}
	
	.session-item:hover {
		background-color: #f9f9f9;
	}
	
	.session-item.active {
		background-color: #e8f0fe;
		border-left: 3px solid #1890ff;
	}
	
	.session-header {
		display: flex;
		justify-content: space-between;
		margin-bottom: 8px;
	}
	
	.user-id {
		font-weight: bold;
	}
	
	.session-time {
		font-size: 12px;
		color: #999;
	}
	
	.service-info {
		display: flex;
		justify-content: space-between;
		margin-bottom: 8px;
	}
	
	.service-id {
		font-size: 14px;
	}
	
	.session-status {
		font-size: 12px;
		padding: 2px 6px;
		border-radius: 10px;
	}
	
	.status-active {
		background-color: #e8f7ee;
		color: #52c41a;
	}
	
	.status-ended {
		background-color: #f5f5f5;
		color: #999;
	}
	
	.status-transferring {
		background-color: #fff3e8;
		color: #fa8c16;
	}
	
	.session-preview {
		font-size: 12px;
		color: #666;
		white-space: nowrap;
		overflow: hidden;
		text-overflow: ellipsis;
	}
	
	.chat-container {
		flex: 1;
		display: flex;
		flex-direction: column;
	}
	
	.chat-header {
		padding: 16px;
		background-color: #f9f9f9;
		border-bottom: 1px solid #eee;
	}
	
	.session-title {
		font-size: 16px;
		font-weight: bold;
		margin-bottom: 8px;
		display: block;
	}
	
	.session-info {
		font-size: 14px;
		color: #666;
	}
	
	.session-actions {
		margin-top: 8px;
		display: flex;
	}
	
	.action-btn {
		margin-right: 8px;
		font-size: 12px;
		padding: 4px 8px;
	}
	
	.chat-messages {
		flex: 1;
		padding: 16px;
		overflow-y: auto;
	}
	
	.message-item {
		margin-bottom: 16px;
		max-width: 80%;
	}
	
	.user-message {
		align-self: flex-start;
	}
	
	.service-message {
		align-self: flex-end;
		margin-left: auto;
	}
	
	.message-header {
		display: flex;
		justify-content: space-between;
		margin-bottom: 4px;
		font-size: 12px;
		color: #999;
	}
	
	.message-content {
		background-color: #f5f5f5;
		padding: 12px;
		border-radius: 8px;
		position: relative;
	}
	
	.user-message .message-content {
		background-color: #f5f5f5;
	}
	
	.service-message .message-content {
		background-color: #e8f0fe;
	}
	
	.no-messages, .no-data, .chat-placeholder {
		display: flex;
		justify-content: center;
		align-items: center;
		height: 100%;
		color: #999;
	}
	
	.btn {
		padding: 8px 16px;
		border-radius: 4px;
		border: none;
		cursor: pointer;
	}
	
	/* 转接模态框样式 */
	.transfer-modal {
		position: fixed;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
		display: flex;
		justify-content: center;
		align-items: center;
		z-index: 999;
	}
	
	.modal-mask {
		position: absolute;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
		background-color: rgba(0, 0, 0, 0.5);
	}
	
	.modal-content {
		position: relative;
		width: 80%;
		max-width: 500px;
		background-color: white;
		border-radius: 8px;
		overflow: hidden;
	}
	
	.modal-header {
		padding: 16px;
		border-bottom: 1px solid #eee;
		display: flex;
		justify-content: space-between;
		align-items: center;
	}
	
	.modal-title {
		font-size: 18px;
		font-weight: bold;
	}
	
	.modal-close {
		font-size: 24px;
		cursor: pointer;
	}
	
	.modal-body {
		padding: 16px;
	}
	
	.form-group {
		margin-bottom: 16px;
	}
	
	.form-label {
		display: block;
		margin-bottom: 8px;
		font-weight: bold;
	}
	
	.picker-value {
		padding: 8px 12px;
		border: 1px solid #ddd;
		border-radius: 4px;
	}
	
	.form-textarea {
		width: 100%;
		height: 100px;
		padding: 8px;
		border: 1px solid #ddd;
		border-radius: 4px;
	}
	
	.modal-footer {
		padding: 16px;
		border-top: 1px solid #eee;
		display: flex;
		justify-content: flex-end;
	}
	
	.cancel-btn {
		background-color: #f5f5f5;
		margin-right: 8px;
	}
	
	.confirm-btn {
		background-color: #1890ff;
		color: white;
	}
</style> 